from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, CompositeAudioClip, afx
import os
from pathlib import Path


def extract_filename(file_path):
    files = file_path.split('/')
    return files[len(files) - 1]


def ds(video_file, audio_file):
    # 需添加背景音乐的视频
    video_clip = VideoFileClip(video_file)
    # 提取视频对应的音频，并调节音量
    # video_audio_clip = video_clip.audio.volumex(0.8)

    # 背景音乐
    audio_clip = AudioFileClip(str(audio_file)).volumex(0.8)
    # 设置背景音乐循环，时间与视频时间一致
    audio = afx.audio_loop(audio_clip, duration=video_clip.duration)
    # 视频声音和背景音乐，音频叠加
    audio_clip_add = CompositeAudioClip([audio])

    # 视频写入背景音
    final_video = video_clip.set_audio(audio_clip_add)

    result = 'buff/8_finally/' + extract_filename(video_file)

    # 将处理完成的视频保存
    final_video.write_videofile(result, audio_codec='aac')
    # finalclip.write_videofile('拼接123.mp4', audio_codec='aac')

def find_audio(fileName):
    directory = 'buff/7_merge_audio'
    path = Path(directory)
    for file in path.glob('**/*'):
        if file.is_file() and fileName in file.name:
            return file

def delete_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"文件 {file_path} 已成功删除")
    else:
        print(f"文件 {file_path} 不存在")

# 1 遍历原始视频目录
def deal_6_video_srt(videoDirs):
    for root, dirs, files in os.walk(videoDirs):
        for file in files:
            # 获取文件的完整路径
            video_file_path = os.path.join(root, file)

            # 获取文件的相对路径
            video_relative_path = os.path.relpath(video_file_path, videoDirs)

            # 使用split()函数拆分相对路径，并将文件名的部分用下划线连接
            parts = video_relative_path.split(os.path.sep)
            formatted_name = '_'.join(parts)
            filename_without_ext = os.path.splitext(formatted_name)[0]
            # 打印格式化后的文件名
            # print(formatted_name)
            # print(filename_without_ext)
            if filename_without_ext == '.DS_Store':
                continue;
            audio = find_audio(filename_without_ext)
            if audio:
                ds(str(video_file_path), audio)
                delete_file(audio)
                delete_file(video_file_path)


# 遍历目录"6_mp4_srt"下的文件
os.environ['IMAGEMAGICK_BINARY'] = '/usr/local/bin/convert'
deal_6_video_srt("buff/6_mp4_srt")
# IMAGEMAGICK_BINARY = '/usr/local/bin/convert'
# PYTHONUNBUFFERED=1;IMAGEMAGICK_BINARY=/usr/local/bin/convert

